package main

import (
	"fmt"
	"go-locks/pessimistic-lock/db"
	"go-locks/pessimistic-lock/proto"
	"go-locks/pessimistic-lock/service"
	"google.golang.org/grpc"
	"log"
	"net"
)

func main() {
	db.InitDB()
	server := grpc.NewServer()
	proto.RegisterStockServer(server, &service.Server{})
	//port, err := GetFreePort()
	//if err != nil {
	//	log.Fatalf("获取空闲端口失败: %s", err.Error())
	//}
	port := 8088
	listen, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
	log.Println("Port: ", port)
	if err != nil {
		log.Fatalf("监听端口失败: %s", err.Error())
	}
	_ = server.Serve(listen)
}

// GetFreePort 获取本机的空闲端口
func GetFreePort() (int, error) {
	addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
	if err != nil {
		return 0, err
	}
	listen, err := net.ListenTCP("tcp", addr)
	if err != nil {
		return 0, err
	}
	defer listen.Close()
	return listen.Addr().(*net.TCPAddr).Port, nil
}
